package com.abc.robot01.activity

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.abc.robot01.R

import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.sp
import com.abc.robot01.activity.compose.Checkbox01
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.bean.RenderQueueData
import com.abc.robot01.vivemodel.RenderViewModel
import com.abc.robot01.vivemodel.getTotal
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage
import java.math.BigDecimal
import java.math.RoundingMode


/**
 * 渲染
 */
class RenderActivity : BaseVoiceActivity() {

    private val viewModel: RenderViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.designPackageId.value = intent.getStringExtra("designPackageId")!!
        viewModel.housePlansDataId.value = intent.getStringExtra("housePlansDataId")!!
        viewModel.housePlansId.value = intent.getStringExtra("housePlansId")!!
        viewModel.load()
        setContent {
            val scrollState = rememberScrollState()
            MaterialTheme {
                Box {
                    Image(painter = painterResource(id = R.drawable.z1), contentDescription = "")
                    Row(modifier = Modifier.padding(30.px)) {
                        BackButton{
                            this@RenderActivity.finish()
                        }
                        Spacer(modifier = Modifier.width(82.px))
                        Column(modifier = Modifier
                            .fillMaxHeight()
                            .width(1400.px)) {
                            BasicText(
                                text = "渲染",
                                style = TextStyle(
                                    fontSize = 30.mysp,
                                    color = Color.Black,
                                    fontWeight = FontWeight.Bold
                                ),
                            )
                            Spacer(modifier = Modifier.height(30.px))
                            Column(
                                Modifier
                                    .verticalScroll(scrollState)
                                    .fillMaxSize(),
                                verticalArrangement = Arrangement.spacedBy(30.px)
                            ) {
                                Title1()
                                Title2()
                                Title3("渲染费用")
                            }
                        }
                    }
                    CenteredRowDemo()
                }
            }
        }
        Log.e(TAG, "onCreate");
    }

    @Composable
    fun Title1() {
        Title(title = "用户信息") {
            Row(verticalAlignment = Alignment.CenterVertically) {
                BasicText(
                    text = "用户名称",
                    style = TextStyle(
                        fontSize = 26.mysp,
                        color = MYBLACK
                    ),
                )
                Spacer(modifier = Modifier.width(20.px))
                val name = remember {  viewModel.userName}
                CustomStyledTextField2(name, textColor = MYBLACK_Percent5)

                Spacer(modifier = Modifier.width(60.px))
                BasicText(
                    text = "手机号",
                    style = TextStyle(
                        fontSize = 26.mysp,
                        color = MYBLACK
                    ),
                )
                Spacer(modifier = Modifier.width(20.px))
                val phone = remember { viewModel.customerPhone }
                CustomStyledTextField2(phone, textColor = MYBLACK_Percent5)
            }
        }
    }

    /**
     *  渲染设置
     */
    @OptIn(ExperimentalGlideComposeApi::class)
    @Composable
    fun Title2() {
        Title(title = "渲染设置") {
            Row(verticalAlignment = Alignment.CenterVertically) {
                // 红色的星号，表示必填
                Text(
                    text = "*",
                    color = Color.Red,
                    fontSize = 7.sp, // 可以根据需要调整字体大小
                )

                BasicText(
                    text = "渲染名称",
                    style = TextStyle(
                        fontSize = 26.mysp,
                        color = Color(0xFF000000)
                    ),
                )
                Spacer(modifier = Modifier.width(20.px))
                val name = remember { viewModel.houseName }
                CustomStyledTextField2(name, textColor = MYBLACK_Percent5)
            }

            Row(
                verticalAlignment = Alignment.CenterVertically, modifier = Modifier
                    .padding(start = 48.px, end = 108.px)
                    .background(Color.Transparent)
            ) {
                // 红色的星号，表示必填
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        text = "*",
                        color = Color.Red,
                        fontSize = 7.sp, // 可以根据需要调整字体大小
                    )
                    BasicText(
                        text = "空间",
                        style = TextStyle(
                            fontSize = 26.mysp,
                            color = Color(0xFF000000)
                        ),
                    )
                }
                Spacer(modifier = Modifier.width(20.px))
                Space()
            }

            Spacer(modifier = Modifier.height(30.px))

            //氛围外景 开始
            Row(verticalAlignment = Alignment.CenterVertically) {
                // 红色的星号，表示必填
                Text(
                    text = "*",
                    color = Color.Red,
                    fontSize = 7.sp, // 可以根据需要调整字体大小
                )

                BasicText(
                    text = "氛围外景",
                    style = TextStyle(
                        fontSize = 26.mysp,
                        color = Color(0xFF000000)
                    ),
                )
                Spacer(modifier = Modifier.width(20.px))

                Column {
                    val radioOptions by viewModel.skyBoxList.collectAsState()
                    val selectedOption  =  remember { viewModel.selectedSkyBoxName }
                        Row(horizontalArrangement = Arrangement.spacedBy(20.px)) {
                            radioOptions.forEach {
                                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                    GlideImage(
                                        model = it.imgUrl.trim(),
                                        contentDescription ="",
                                        modifier = Modifier.size(192.px, 108.px)
                                    )
                                    Spacer(modifier = Modifier.height(10.px))
                                    CustomRadioButtonDemo2(it.name, selectedOption)
                                }
                            }
                        }
                }
            }   //氛围外景 结束

            Spacer(modifier = Modifier.height(30.px))

        //渲染方式 开始
        Row(verticalAlignment = Alignment.CenterVertically) {
            // 红色的星号，表示必填
            Text(
                text = "*",
                color = Color.Red,
                fontSize = 7.sp, // 可以根据需要调整字体大小
            )

            BasicText(
                text = "渲染方式",
                style = TextStyle(
                    fontSize = 26.mysp,
                    color = Color(0xFF000000)
                ),
            )
            Spacer(modifier = Modifier.width(20.px))
                CustomRadioButtonDemo()
            Spacer(modifier = Modifier.width(10.px))
            BasicText(
                text = "白天时间段08:30 - 22:59，默认日间渲染，其他时间段屏蔽日间渲染",
                style = TextStyle(
                    fontSize = 20.mysp,
                    color = Color(0xFFFB870C)
                ),
            )
        }   //渲染方式 结束
            More()
    }
}
    /**
     *  还有多少人
     */
    @Composable
    fun More(){
        val more by remember { viewModel.more }
        Row(verticalAlignment = Alignment.CenterVertically) {
            Spacer(modifier = Modifier.width(128.px))
            Card(
                colors = CardDefaults.cardColors().copy(containerColor = MYBLACK_Percent5),
                modifier= Modifier
                    .padding(0.dp)
                    .size(1134.px, 60.px)
                ,shape= RoundedCornerShape(10.px)
            ) {
                Spacer(modifier = Modifier.height(20.px))
                Row {
                    Spacer(modifier = Modifier.width(20.px))
                    BasicText(
                        text = "前面还有",
                        style = TextStyle(
                            fontSize = 20.mysp,
                            color = MYBLACK,
                        )
                    )
                    BasicText(
                        text = more,
                        style = TextStyle(
                            fontSize = 20.mysp,
                            color = Color.Red,
                        )
                    )
                    BasicText(
                        text = "人等待渲染",
                        style = TextStyle(
                            fontSize = 20.mysp,
                            color = MYBLACK,
                        )
                    )
                    Spacer(modifier = Modifier.width(40.px))
                    BasicText(
                        text = "夜间渲染",
                        style = TextStyle(
                            fontSize = 20.mysp,
                            color = MYBLACK,
                        )
                    )
                    Spacer(modifier = Modifier.width(10.px))

                    BasicText(
                        text = "当日22:00 - 次日08:30分之间渲染，价格*0.5",
                        style = TextStyle(
                            fontSize = 20.mysp,
                            color = MYBLACK_Percent60,
                        )
                    )
                    Spacer(modifier = Modifier.width(40.px))

                    BasicText(
                        text = "加急渲染",
                        style = TextStyle(
                            fontSize = 20.mysp,
                            color = MYBLACK,
                        )
                    )
                    Spacer(modifier = Modifier.width(10.px))
                    BasicText(
                        text = "优先开始渲染，价格*1.5",
                        style = TextStyle(
                            fontSize = 20.mysp,
                            color = MYBLACK_Percent60,
                        )
                    )
                }
            }
        }
    }

    /**
     *  渲染费用
     */
    @Composable
    fun Title3(title:String) {
        Title(title = title) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                // 红色的星号，表示必填
                Text(
                    text = "*",
                    color = Color.Red,
                    fontSize = 7.sp, // 可以根据需要调整字体大小
                )

                BasicText(
                    text = "渲染数量",
                    style = TextStyle(
                        fontSize = 26.mysp,
                        color = Color(0xFF000000)
                    ),
                )
                Spacer(modifier = Modifier.width(20.px))
                val name = remember {  viewModel.totalQuantity }
                CustomStyledTextField3(last = "张",text = name, textColor = Color(0xff000000))

                Spacer(modifier = Modifier.width(40.px))

                // 红色的星号，表示必填
                Text(
                    text = "*",
                    color = Color.Red,
                    fontSize = 7.sp, // 可以根据需要调整字体大小
                )

                BasicText(
                    text = "渲染费用",
                    style = TextStyle(
                        fontSize = 26.mysp,
                        color = Color(0xFF000000)
                    ),
                )
                Spacer(modifier = Modifier.width(20.px))
                val name2 = remember {  viewModel.totalAmount}
                CustomStyledTextField3(last = "元",text = name2, textColor = Color(0xff000000))
            }
            Row(
                verticalAlignment = Alignment.Top, modifier = Modifier
                    .padding(start = 48.px, end = 108.px)
                    .background(Color.Transparent)
            ) {
            }
            Spacer(modifier = Modifier.height(30.px))
        }
    }

    @Composable
    fun CustomRadioButtonDemo() {
        val radioOptions: List<RenderQueueData> by viewModel.modeList.collectAsState()
        if(radioOptions.isNotEmpty()) {
            var selectedOption by remember { mutableStateOf(radioOptions[0]) } // 默认选中第一个选项
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(20.px)
            ) {
                radioOptions.forEach { option ->
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        CustomRadioButton(
                            selected = selectedOption == option,
                            onClick = {
                                selectedOption = option
                                viewModel.selectedOption.value = option.name
                              val a  =  radioOptions.find { it.name ==   viewModel.selectedOption.value }
                                a?.let {
                                    Log.e(TAG, "获取渲染价格配置: "+a.name)
                                    Log.e(TAG, "获取渲染价格配置: "+a.ratio)
//                                    viewModel.fee.doubleValue *= a.ratio
//                                    viewModel.totalQuantity.value = items.filter { it.selected }.size.toString()

//                                    items.filter { it.selected }.forEach {
//                                        Log.e(TAG, "子费用: "+ it.renderPrice)
//                                    }
                                    viewModel.totalAmount.value =  getTotal(viewModel.houseTypeList.value)
                                }
                                      },
                            size = 30.px // 自定义 RadioButton 的尺寸
                        )
                        Spacer(modifier = Modifier.width((10.px)))
                        BasicText(
                            text = option.name,
                            style = TextStyle(
                                fontSize = 26.mysp,
                                color = Color(0xFF000000)
                            ),
                        )
                    }
                }
            }
        }
    }

    @Composable
    fun BoxScope.CenteredRowDemo() {
        val totalAmount by remember { viewModel.totalAmount}
        Row(
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .fillMaxWidth()
                .height(74.px) // 设置行的高度为100dp
                .background(Color.White),
            verticalAlignment = Alignment.CenterVertically // 设置垂直居中
        ) {
            Spacer(modifier = Modifier.weight(100f))
            Row(verticalAlignment=Alignment.Bottom) {
                BasicText(
                    text = "应付合计",
                    style = TextStyle(
                        fontSize = MyFont_Size,
                        color = Color.Black,
                        textAlign = TextAlign.Center,
                    ),
                )
                Spacer(modifier = Modifier.width(20.px))
                BasicText(
                    text = "¥",
                    style = TextStyle(
                        fontSize = 20.mysp,
                        color = Color.Blue,
                        textAlign = TextAlign.Center,
                        fontWeight = FontWeight.Bold
                    ),
                )
                BasicText(
                    text = totalAmount,
                    style = TextStyle(
                        fontSize = 38.mysp,
                        color = Color.Blue,
                        textAlign = TextAlign.Center,
                        fontWeight = FontWeight.Bold
                    ),
                )
                BasicText(
                    text = "元",
                    style = TextStyle(
                        fontSize = 20.mysp,
                        color = Color.Blue,
                        textAlign = TextAlign.Center,
                    ),
                )
            }

            Spacer(modifier = Modifier.width(100.px))
            MyButton01(text = "取消",textColor = Color.Black){
                finish()
            }
            Spacer(modifier = Modifier.width(20.px))
            MyButton01(text = "支付渲染",
                containerColor= MYBLUE,
                textColor = Color.White){
                    submit()
            }
            Spacer(modifier = Modifier.width(30.px))
        }
    }

    /**
     *   定义一个title ,下面是内容 ,
     *   例子可以查看: https://www.figma.com/design/7YtLSgj000mxvLmuyPJynl/%E4%B8%80%E6%9D%9F%E5%85%89%E7%A7%91%E6%8A%80--%E6%9C%BA%E5%99%A8%E4%BA%BA%E7%AB%AF?node-id=385-11603&node-type=CANVAS&t=K4gI0sJdooGo8tU4-0
     */
    @Composable
    fun Title(title:String="用户信息",content: @Composable ColumnScope.() -> Unit) {
            Card(
                colors = androidx.compose.material3.CardDefaults.cardColors(
                    containerColor = Color.White // 设置背景色为白色
                ),
                modifier = Modifier
                    .width(1400.px)
//                    .heightIn(min = 90.px)
                    .background(Color.Transparent),
                shape = RoundedCornerShape(20.px
                )
            ) {
                Column(modifier = Modifier
                    .padding(start = 30.px,top=30.px, bottom = 30.px)) {
                    Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier
                        .background(Color.Transparent)
                        .clickable {
                        }) {
                        BasicText(
                            text = title,
                            style = TextStyle(
                                fontSize = MyFont_Size,
                                color = Color.Black,
                                fontWeight = FontWeight.Bold
                            ),
                        )
                    }
                        Spacer(modifier = Modifier.height(30.px))
                    content()
                }
            }
        }

    private fun submit(){
        if(viewModel.houseName.value.trim() == ""){
            Toast.makeText(this@RenderActivity, "请填写渲染名称", Toast.LENGTH_LONG).show()
            return
        }
        viewModel.submit()
        startActivity<ZhifuActivity>(){
            val renderRoomIds = viewModel.houseTypeList.value.filter { it.selected }
                .joinToString(",") { it.id }
            Log.e(TAG, "renderRoomIds: "+renderRoomIds)
            val sky =  viewModel.skyBoxList.value.find { it.name == viewModel.selectedSkyBoxName.value }!!.skyBoxId
            putExtra("skyBoxId",sky)
            putExtra("renderRoomIds",renderRoomIds)
            putExtra("userName",viewModel.userName.value)
            putExtra("name",viewModel.houseName.value)
            putExtra("customerPhone",viewModel.customerPhone.value)
            putExtra("designPackageId",viewModel.designPackageId.value)
            putExtra("housePlansId",viewModel.housePlansId.value)
            putExtra("housePlansDataId",viewModel.housePlansDataId.value)
            putExtra("fee",viewModel.totalAmount.value)
        }
    }

    companion object {
        val TAG = "XuanRanActivity"
    }

    /**
     * 空间
     */
    @Composable
    fun Space() {
        var items by remember { viewModel.houseTypeList
        }

        // Group items into chunks of 6
        val groupedItems = items.chunked(9)

        Column(modifier = Modifier.fillMaxSize()) {
            // Iterate through each group and create a Row for each
            for (group in groupedItems) {
                Row(modifier = Modifier, horizontalArrangement = Arrangement.SpaceBetween) {
                    for (item in group) {
                        Checkbox01(
                            modifier = Modifier
                                .size(30.px),
                            checked = item.selected,
                            onCheckedChange = { it2 ->
                                Log.e(TAG, "onCheckedChange: "+ it2)
                                items = items.map {
                                    if (it.id == item.id) it.copy(selected = it2) else it
                                }.toMutableList()

                                viewModel.totalQuantity.value = items.filter { it.selected }.size.toString()

//                                items.filter { it.selected }.forEach {
//                                    Log.e(TAG, "子费用: "+ it.renderPrice)
//                                }
//
//                                var sum = BigDecimal("0.00")
//                                items.filter { it.selected }.forEach {
//                                    val value = BigDecimal(it.renderPrice.toString())
//                                    sum = sum.add(value)
//                                }
//                                Log.e(TAG, "总费用: "+  sum)
//                                 sum = sum.setScale(2, RoundingMode.HALF_DOWN)
                                viewModel.totalAmount.value =  getTotal(items)
                                Log.e(TAG, "总费用: "+  viewModel.totalAmount.value)
                            }
                        )
                        BasicText(
                            modifier = Modifier.offset(x = 0.dp),
                            text = item.name,
                            style = TextStyle(
                                fontSize = MyFont_Size,
                                color = Color(0xFF000000)
                            ),
                        )
                        Spacer(modifier = Modifier.width(30.px))
                    }
                }
            }
        }
        }
}
